package cn.gdcp.wuziqi;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.icu.util.Measure;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class WuziqiPanel extends View {
    private int mPanelWidth;
    //用int会容易发生精度的丢失
    private float mLineHeight;
    private int MAX_LINE = 10;
    private int MAX_COUNT_IN_LINE = 5;

    private Paint mPaint = new Paint();

    private Bitmap mWhitePiece ;
    private Bitmap mBlackPiece ;

    //比例，让棋子的大小是行高的3/4,有1/4的空隙
    private float ratioPieceOfLineHeight = 3*1.0f/4;

    //b白棋先手，当期轮到白棋
    private boolean mIsWhite = true;
    private ArrayList<Point> mWhiteArray = new ArrayList<>();
    private ArrayList<Point> mBlackArray = new ArrayList<>();

    private boolean mIsGameOver;
    private boolean mIsWhiteWinner;


    public WuziqiPanel(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //setBackgroundColor(0x44ff0000);
        init();
    }

    private void init() {
        mPaint.setColor(0x88000000);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStyle(Paint.Style.STROKE);

        //两棋子间应当存在间隙，适配棋盘
        mWhitePiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_w2);
        mBlackPiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_b1);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = Math.min(widthSize,heightSize);

        if (widthMode == MeasureSpec.UNSPECIFIED){
            width = heightSize;
        }else if(heightMode == MeasureSpec.UNSPECIFIED){
            width = widthSize;
        }
        setMeasuredDimension(width,width);
    }

    //跟尺寸相关的
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mPanelWidth = w;
        mLineHeight = mPanelWidth * 1.0f/MAX_LINE;

        //目标宽度
        int pieceWidth = (int) (mLineHeight*ratioPieceOfLineHeight);
        //棋子的尺寸跟随着控件的变化，通过比例ratioPieceOfLineHeight
        mWhitePiece = Bitmap.createScaledBitmap(mWhitePiece,pieceWidth,pieceWidth,false);
        mBlackPiece = Bitmap.createScaledBitmap(mBlackPiece,pieceWidth,pieceWidth,false);
    }

    //落子
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //判断
        if(mIsGameOver) return false;//表明态度，不感兴趣
        int action = event.getAction();
        //DOWN只是表明一下态度，与父View，可能会造成滑动与落子的事件偏差
        //if (action == MotionEvent.ACTION_DOWN){
        if (action == MotionEvent.ACTION_UP){
            int x = (int) event.getX();
            int y = (int) event.getY();

            //将X,Y封装成Point,每一个Point就代表一个棋子的位置，根据x,y确定点
            //Point p = new Point(x,y);会造成点的散乱性
            Point p = getValidPoint(x,y);

            //判断该位置是否已经有棋子了
            //contains比较的是Point对象的值
            if(mWhiteArray.contains(p) || mBlackArray.contains(p)){
                return false;
            }
            if (mIsWhite){
                mWhiteArray.add(p);
            }else{
                mBlackArray.add(p);
            }
            //请求重绘
            invalidate();
            mIsWhite = !mIsWhite;

            //return  true;//（DOWN的时候）告诉父View，如果有Touch事件是在子View上的话，将该事件交给自己处理，即表明自己的态度
        }

        return true;
    }

    private Point getValidPoint(int x, int y) {
        //点击偏移量小的，取整，使棋子整齐
        return new Point((int)(x/mLineHeight),(int) (y/mLineHeight));
    }

    //绘制操作
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPieces(canvas);
        checkGameOver();
    }

    private void checkGameOver() {
        //判断
        boolean whiteWin = checkFiveInLine(mWhiteArray);
        boolean blackWin = checkFiveInLine(mBlackArray);
        if(whiteWin || blackWin){
            mIsGameOver = true;
            mIsWhiteWinner = whiteWin;

            //当GameOver的时候，通过接口去回调出去
            //GameOverListener到GameOver，将结果传出去
            String text = mIsWhiteWinner?"白棋胜利":"黑棋胜利";
            Toast.makeText(getContext(),text,Toast.LENGTH_SHORT).show();
        }
    }

    private boolean checkFiveInLine(List<Point> points) {
        //分为四种情况,横向，纵向，右倾，左倾
        for(Point p:points){
            int x=p.x;
            int y=p.y;

            boolean win = checkHorizontal(x,y,points);
            if (win) return true;
            win = checkVertical(x,y,points);
            if (win) return true;
            win = checkLeftDiagonal(x,y,points);
            if (win) return true;
            win = checkRightDiagonal(x,y,points);
            if (win) return true;

        }
        return false;
    }

    /**
     * 判断x,y位置的棋子，是否横向有相邻的五个一致
     */

    private boolean checkHorizontal(int x, int y, List<Point> points) {
        //根据当前的棋子，往左数，再往右
        int count =1;
        //左
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            //所给的point中，所有棋子当中是否包含左边的第一个棋子
            //其中左边的第一个棋子Point，也就是它的横坐标，它给出的X-1，第二个X-2。。。。
            if(points.contains(new Point(x-i,y))){
                count++;
            }else{
                //结束循环
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE) return true;
        //右
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
           if(points.contains(new Point(x+i,y))){
                count++;
            }else{
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE) return true;
        return false;
    }


    private boolean checkRightDiagonal(int x, int y, List<Point> points) {
        int count =1;
        //上
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x-i,y-i))){
                count++;
            }else{
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE) return true;
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x+i,y+i))){
                count++;
            }else{
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE) return true;
        return false;
    }
    private boolean checkLeftDiagonal(int x, int y, List<Point> points) {
        int count =1;
        //上
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x-i,y+i))){
                count++;
            }else{
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE) return true;
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x+i,y-i))){
                count++;
            }else{
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE) return true;
        return false;
    }


    private boolean checkVertical(int x, int y, List<Point> points) {
        int count =1;
        //上
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x,y-i))){
                count++;
            }else{
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE) return true;
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x,y+i))){
                count++;
            }else{
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE) return true;
        return false;
    }

    //绘制棋子
    private void drawPieces(Canvas canvas) {
        for(int i=0,n=mWhiteArray.size();i<n;i++){
            //拿到棋子
            Point whitePoint = mWhiteArray.get(i);
            canvas.drawBitmap(mWhitePiece,
                    (whitePoint.x+(1-ratioPieceOfLineHeight)/2)*mLineHeight,
                    (whitePoint.y+(1-ratioPieceOfLineHeight)/2)*mLineHeight,null);
        }
        for(int i=0,n=mBlackArray.size();i<n;i++){
            Point blackPoint = mBlackArray.get(i);
            canvas.drawBitmap(mBlackPiece,
                    (blackPoint.x+(1-ratioPieceOfLineHeight)/2)*mLineHeight,
                    (blackPoint.y+(1-ratioPieceOfLineHeight)/2)*mLineHeight,null);
        }
    }

    //绘制棋盘
    private void drawBoard(Canvas canvas) {
        int w = mPanelWidth;
        float lineHeight = mLineHeight;
        for(int i=0;i<MAX_LINE;i++){
            //横线
            //初始坐标
            int startX = (int)(lineHeight/2);
            int endX = (int)(w-lineHeight/2);
            //纵坐标
            int y = (int) ((0.5+i)*lineHeight);
            canvas.drawLine(startX,y,endX,y,mPaint);
            canvas.drawLine(y,startX,y,endX,mPaint);
        }
    }


    public void start(){
        mWhiteArray.clear();
        mBlackArray.clear();
        mIsGameOver = false;
        mIsWhiteWinner = false;
        invalidate();
    }



    //进行View的存储与恢复时布局文件一定要有id
    private static  final String INSTANCE = "instance";
    private static  final String INSTANCE_GAME_OVER="instance_game_over";
    private static  final String INSTANCE_WHITE_ARRAY="instance_white_array";
    private static  final String INSTANCE_BLACK_ARRAY="instance_black_array";

    //对当前棋子的位置进行存储
    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE,super.onSaveInstanceState());
        bundle.putBoolean(INSTANCE_GAME_OVER,mIsGameOver);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY,mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY,mBlackArray);
        return bundle;
    }

    //当Activity重建的时候，View会去调用onRestoreInstanceState，恢复棋盘
    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        //是否是Bundle类型，如果是的话，代表是我们自己设置的
        if(state instanceof Bundle){
            //把值取出来
            Bundle bundle = (Bundle) state;
            mIsGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            mWhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mBlackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }

        super.onRestoreInstanceState(state);
    }
}
